library common_tool;

import 'dart:io';

import 'package:dart_ping/dart_ping.dart';
import 'package:dart_ping_ios/dart_ping_ios.dart';
import 'package:flutter/foundation.dart';
import 'package:get_storage/get_storage.dart';
import 'local_clock.dart';

// ping 的url
const String baiduUrl = 'baidu.com';
const String googleUrl = 'google.com';
// Ping 间隔180秒
const int interval = 180;
const int debugInterval = 30;
// 本地存储的key
const String savedDataKey = 'savedDataKey';

class PingTool {

  // 最后一次ping的时间
  static DateTime? lastPingTime;

  static Function(Map log)? onPingData;

  // 通过最后一次ping的间隔
  static bool isPinging() {
    return false;
  }

  // 开始ping
  static startPing() {

    if (Platform.isIOS) {
      DartPingIOS.register();
    }
    /*1.初始化*/
    final ping = Ping(
      kDebugMode ? baiduUrl : googleUrl,
      interval: kDebugMode ? debugInterval : interval,
    );

    ping.stream.listen((event) {

      List list = PingTool.savedDataList ??= [];

      DateTime currentTimeStamp = LocalClock.getNetworkUTCDateTime() ?? DateTime.now();

      Map log = {};
      log['address'] = kDebugMode ? baiduUrl : googleUrl;
      if (event.error != null) {
        log["ping"] = -1; // event.error.toString();
      } else if (event.response != null) {
        Duration? duration = event.response?.time;
        if (duration == null) {
          log["ping"] = -1;
        } else {
          log["ping"] = duration.inMilliseconds;
        }
      }
      log["clientTime"] = currentTimeStamp.millisecondsSinceEpoch;
      if (onPingData != null) {
        onPingData!(log);
      }

      if (list.length >= 50) {
        list.removeRange(0, 25);
      }

      list.add(log);
    });
  }

  /// 缓存上传失败的数据
  static List? get savedDataList => GetStorage().read(savedDataKey);
  static set savedDataList(List? savedDataList) =>
      GetStorage().write(savedDataKey, savedDataList);

}